package madixin.t451;

import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

class Solution {
    public String frequencySort(String s) {
        Map<Character, Integer> freqMap = new HashMap<>();
        for (int i = 0; i < s.length(); i++) {
            freqMap.put(s.charAt(i), freqMap.getOrDefault(s.charAt(i), 0) + 1);
        }

        for (Character key : freqMap.keySet()) {
            System.out.println(key + " : " + freqMap.get(key));
        }
        List<Character>[] buckets = new List[s.length() + 1];
        for (Character key : freqMap.keySet()) {
            int frequence = freqMap.get(key);
            if (buckets[frequence] == null) {
                buckets[frequence] = new LinkedList<Character>();
            }
            buckets[frequence].add(key);
        }
        StringBuilder sb = new StringBuilder();
        for (int i = buckets.length - 1; i > 0; i--) {
            if (buckets[i] != null) {
                for (Character c : buckets[i]) {
                    for (int j = 0; j < i; j++) {
                        sb.append(c);
                    }
                }
            }
        }
        return sb.toString();
    }

    public static void main(String[] args) {
        Solution s = new Solution();
        System.out.println(s.frequencySort("tree"));
        System.out.println(s.frequencySort("cccaaa"));
        System.out.println(s.frequencySort("Aabba"));
    }
}